package service.bboard;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import common.AnonMath;
import common.Point;
import common.Settings;

import iface.PublicSharesIface;

public class BulletinBoard implements PublicSharesIface {

	private Map<Integer, Point[]> _board;


	public BulletinBoard(){
		this._board = new HashMap<Integer, Point[]>();
	}


	@Override
	public Point[] getPublicShareList(Integer clientID) {
		if (!this._board.containsKey(clientID)){
			System.out.println("BBOARD: invalid client ID requested!");
			return null;
		}
		return this._board.get(clientID);
	}


	public Integer[] getListOfClients() {
		int i,sz;
		Integer[] listOfClients;
		Set<Integer> keys = this._board.keySet();
		sz = keys.size();
		i = 0;
		listOfClients = new Integer[sz];
		Iterator<Integer> it = keys.iterator();

		while (it.hasNext()) {
			listOfClients[i] = it.next();
			i++;
		}
		return listOfClients;
	}

	@Override
	public Boolean submitClientShare(Integer clientID, Point cliShare) {
		Point[] clientShares = null;
		Point[] updatedClientShares;
		int i;

		if (this._board.containsKey(clientID)){
			clientShares = this._board.get(clientID);


			for ( i = 0; i < clientShares.length; i++) {
				if (clientShares[i].isEqual(cliShare))
					return false;
			}
			updatedClientShares = new Point[clientShares.length+1];
			for ( i = 0; i < clientShares.length ; i++) {
				updatedClientShares[i] = clientShares[i];
			}
			updatedClientShares[updatedClientShares.length-1] = cliShare;

			this._board.put(clientID, updatedClientShares);
			return true;
		}
		updatedClientShares = new Point[]{cliShare};
		this._board.put(clientID, updatedClientShares);

		return true;
	}

	public Integer getUserSecret(Integer clientID) {
		if (this.hasEnoughShares(clientID))
			return AnonMath.interpolate(this._board.get(clientID));
		return null;
	}


	public Boolean hasEnoughShares(Integer clientID) {
		if (this._board.containsKey(clientID))
			return (this._board.get(clientID).length >= Settings.threshold);
		return false;
	}



}
